# coding:utf-8

from django.db import models
from django.contrib.auth.models import User
from gettext import gettext as _
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic


class IDataPageManager(models.Manager):
    def get_data(self, owner, page_slug=None):
        page = IDataPage.objects.get(slug=page_slug)
        return self.get_query_set().filter(owner=owner, page=page)

class IDataPage(models.Model):
    slug = models.SlugField(_(u"Системное имя"), help_text=_(u"Имя используется для доступа к странице"))
    name = models.CharField(_(u"Название"), max_length=150)
    owner = models.ForeignKey(User, verbose_name=_(u"Владелец"), related_name="datapages")

    def __unicode__(self):
        return u"%s" % (self.name)

    class Meta:
        verbose_name = _(u"Страница данных")
        verbose_name_plural = _(u"Страницы данных")

class IPageFieldManager ( models.Manager ):

    def create_text_field ( self, key, value, page ):
        text_field = IDataTextField(value = value)
        text_field.save()
        field = IPageField ( key=key, value = value, page=page, content_object=text_field )
        field.save()
        return field
        
    def create_image_field(self, key, value, page):
        image_field = IDataImageField( value = value )
        image_field.save()
        field = IPageField ( key=key, value = value, page=page, content_object=image_field )
        field.save()
        return field

    def page_objects ( self, page ):
        return self.get_queryset().filter ( page = page )
        

class IPageField(models.Model):
    page = models.ForeignKey ( IDataPage, verbose_name=_(u"Страница"), related_name="text_fields")
    key = models.CharField(_(u"Ключ"), max_length=250 )
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    
    objects = IPageFieldManager()
    
    def __unicode__(self):
        return self.key
        
    class Meta:
        unique_together   = ('content_type', 'object_id')
    

class IDataTextField ( models.Model ):
    
    value = models.TextField( _(u"Значение"), blank=True)
    field = generic.GenericRelation(IPageField)

    def __unicode__(self):
        return u"TF = %s" % (self.value)

    class Meta:
        verbose_name = _(u"Поле текстовых данных")
        verbose_name_plural = _(u"Поля текстовых данных")


class IDataImageField(models.Model):
    value = models.ImageField(_(u"Изображение"), upload_to="dataimages/")
    field = generic.GenericRelation(IPageField)


    def __unicode__(self):
        return u"IF = %s" % (self.value.url)

    class Meta:
        verbose_name = _(u"Поле графичиских данных")
        verbose_name_plural = _(u"Поля графичиских данных")
